package com.example.xinlijiankangsys.controller;

import com.example.xinlijiankangsys.service.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/*
 * websocket处理器
 */
@Slf4j
@Component
public class WebSocketController extends TextWebSocketHandler {
    private static WebSocketService webSocketService;
    @Autowired
    public void setWebSocketService(WebSocketService webSocketService) {
        WebSocketController.webSocketService = webSocketService;
    }
    // 在线 存储在标识符----Session
    private static final ConcurrentHashMap<String, WebSocketSession> clientMap = new ConcurrentHashMap<>();
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 访问握手时设置的属性
        Map<String, Object> attributes = session.getAttributes();
        //获取属性值
        Object identityMsgObj = attributes.get("identityMsg");
        Map<String, String> map;
        try {
            if (identityMsgObj instanceof Map) {
                map = (Map<String, String>) identityMsgObj;
                String id = map.get("id");
                log.info("用户id为: {}", id);
                session.getAttributes().put("id",id); // 将 id 存储在 session 的属性中
                //处理连接 并做一些事情
                handleNewConnection(session, id);
                if(id!=null) {
                    //查看消息箱的数据 并发给自己
                    webSocketService.getMsgFromBox(id, clientMap);
                }
            } else {
                log.warn("identityMsg is not of type Map: {}", identityMsgObj);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    public void handleTextMessage(@NotNull WebSocketSession session, TextMessage message) throws Exception {
        String msgLoad=message.getPayload();
        log.info("接收到消息: {}",msgLoad);
        // 从 session 的属性中获取 QQEmail
        String id= (String) session.getAttributes().get("id");
        log.info("当前 发送消息的用户id是 : {}", id);
        webSocketService.processMessage(id,msgLoad,session,clientMap);
    }
    @Override
    public void afterConnectionClosed(@NotNull WebSocketSession session, @NotNull CloseStatus status) throws Exception {
        String id=(String)session.getAttributes().get("id");//获取标识符
        if (id!= null) {
            clientMap.remove(id,session);
            log.info("客户端失去连接,其用户id为: {}", id);
            session.close();
        }
    }
    @Override
    public void handleTransportError(@NotNull WebSocketSession session, Throwable exception) throws Exception {

        String id=(String)session.getAttributes().get("id");//获取标识符
        if (id != null) {
            try {
                log.error("用户id为: {}发生错误: {}", id,exception.getMessage());
            } catch (Exception e) {
                log.error("更新离线时间失败: {}", e.getMessage());
                // 这里可以选择抛出异常或进行其他处理
            } finally {
                try {
                    clientMap.remove(id, session); // 从 clientMap 中移除会话
                    session.close(); // 关闭会话
                } catch (Exception e) {
                    log.error("关闭会话失败: {}", e.getMessage());
                }
            }
        }
    }
    private void handleNewConnection(WebSocketSession session,String userId) throws IOException {
        WebSocketSession existingSession = clientMap.putIfAbsent(userId, session);
        if (existingSession != null) {
            existingSession.close(); // 关闭旧连接
            log.info("关闭旧连接: {}", userId);
        }

    }
}

